import React, {useRef, useEffect } from "react";
import * as echarts from 'echarts';
import './Scss/HomenEcartsShow.scss'

/**
 * @date: 2024-07-19 14:59:43
 * @description: Echarts配置数据
 * @modifyContent:
 * @author: Forever丿顾北
**/
const axisOption = {
  // 图文字体颜色
  textStyle: {
    color: '#333'
  },
  // 提示框
  tooltip: {
    trigger: 'axis',
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '##17b3a3'
      }
    },
    axisLabel: {
      interval: 0,
      color: '#333'
    },
  },
  yAxis: [{
    type: 'value',
    axisLine: {
      lineStyle: {
        color: '##17b3a3'
      }
    }
  }],
  color: ['#2ec7c9', '#b6a2de', '#5ab1ef', '#ffb980', '#d87a80', '#8d98b3'],
  series: []
}

const normalOptions = {
  tooltip: {
    trigger: 'item',
  },
  color: [
    '#0f78f4',
    '#dd536b',
    '#9462e5',
    '#a6a6a6',
    '#e1bb22',
    '#39c362',
    '#3ed1cf'
  ],
  series: []
}

/**
 * @date: 2024-07-19 15:17:51
 * @description: 创建echarts,
 * @param { Object } ${style}: ${样式}
 * @param { * } ${chartData}: ${数据}
 * @param { Boolean } ${isAxiscChart}: ${是否有坐标系}
 * @modifyContent:
 * @author: Forever丿顾北
**/
const HomenEcartsShow = ({style, chartData, isAxiscChart = true}) => {
  // 获取dom实例
  const echartsRef = useRef()
  const echartsObject = useRef(null)
  useEffect(() =>{
    if (echartsRef.current){
      let options = null
      // 销毁之前的实例
      if (echartsObject.current) {
        echartsObject.current.dispose();
      }
      // ecarts初始化
      echartsObject.current = echarts.init(echartsRef.current)
      // 设置对应数据(options)
      if (isAxiscChart) { // 有没有坐标系,如果没有则是饼图
        axisOption.xAxis.data = chartData.xData
        axisOption.series = chartData.series
        options = axisOption
      } else {
        normalOptions.series = chartData.series
        options = normalOptions
      }
      // 设置 ECharts 实例的配置项和数据
      echartsObject.current.setOption(options)
    } else {
      // 当组件卸载时，销毁 ECharts 实例
      if (echartsObject.current) {
        echartsObject.current.dispose();
      }
    }
  },[style, chartData, isAxiscChart])
  
  return (
    <div style={style} ref={echartsRef}></div>
  )
}

export default HomenEcartsShow;